<template>
  <div class="publish">
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: 'hello' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="#">文章管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>文章发布</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card" style="margin-top: 20px">
      <el-form ref="form" :model="post" label-width="80px" :rules="rules">
        <el-form-item label="标题" prop="title">
          <el-input v-model="post.title"></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="post.type">
            <el-radio :label="1">文章</el-radio>
            <el-radio :label="2">视频</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <!-- 富文本框 -->
          <VueEditor :config="config" v-if="post.type == 1" ref="vueEditor" />
          <!-- 视频 -->
          <el-upload
            class="upload-demo"
            action="http://localhost:3000/upload"
            :on-success="uploadVideoSuccess"
            :file-list="fileList"
            v-if="post.type == 2"
            :headers="getToken()"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传视频文件</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="栏目" prop="categories">
          <el-checkbox
            :indeterminate="isIndeterminate"
            v-model="checkAll"
            @change="handleCheckAllChange"
            >全选</el-checkbox
          >
          <div style="margin: 15px 0"></div>
          <el-checkbox-group
            v-model="checkedCategories"
            @change="handleCheckedCategoryChange"
          >
            <el-checkbox
              v-for="item in cateList"
              :label="item.id"
              :key="item.id"
              >{{ item.name }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="封面" prop="cover">
          <el-upload
            action="http://localhost:3000/upload"
            :headers="getToken()"
            list-type="picture-card"
            :on-success="handleCoverSuccess"
            :on-remove="handleRemove"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <!-- <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="" />
          </el-dialog> -->
        </el-form-item>
        <el-button type="primary" @click="publish">文章发布</el-button>
      </el-form>
    </el-card>
  </div>
</template>

<script>
// 下载并引入富文本框插件
import VueEditor from "vue-word-editor";
import "quill/dist/quill.snow.css";
import { getCateList } from "@/apis/category.js";
import { publishPost } from "@/apis/post.js";
export default {
  components: {
    VueEditor,
  },
  data() {
    return {
      isIndeterminate: false,
      checkAll: false,
      cateList: [],
      checkedCategories: [],
      rules: {
        title: [{ required: true, message: "清输入文章标题", trigger: "blur" }],
      },
      fileList: [], // 上传视频文件列表
      post: {
        title: "", // 文章标题
        content: "", // 文章内容
        categories: [], // 所属栏目集合id
        cover: [], // 封面图片
        type: 1, // 1文章 2视频
      },
      // 富文本框配置
      config: {
        // 上传图片的配置
        uploadImage: {
          url: "http://localhost:3000/upload", // 上传文件的服务器处理地址
          name: "file", // 后台所需要的参数接口
          // 添加token的传递,插件本身有异步操作，不会经过我们所添加的拦截器
          headers: this.getToken(),
          // res是结果，insert方法会把内容注入到编辑器中，res.data.url是资源地址
          uploadSuccess(res, insert) {
            // console.log(res);
            insert("http://localhost:3000" + res.data.data.url);
          },
        },

        // 上传视频的配置
        uploadVideo: {
          url: "http://localhost:3000/upload",
          name: "file",
          headers: this.getToken(),
          uploadSuccess(res, insert) {
            // console.log(res);
            insert("http://localhost:3000" + res.data.data.url);
          },
        },
      },
    };
  },
  async mounted() {
    let res = await getCateList();
    console.log("分类栏目", res);
    if (res.status == 200) {
      this.cateList = res.data.data.slice(2);
    }
  },
  methods: {
    // 封面上传成功
    handleCoverSuccess(response) {
      console.log(response);
      if (response.message == "文件上传成功") {
        this.post.cover.push({ id: response.data.id });
      }
    },
    // 封面移除
    handleRemove(file) {
      console.log(file);
      let id = file.response.data.id; // 需要移除的封面id
      for (let i = 0; i < this.post.cover.length; i++) {
        if (id == this.post.cover[i].id) {
          this.post.cover.splice(i, 1);
          break;
        }
      }
    },
    handleCheckedCategoryChange(value) {
      // console.log(value);
      let checkedCount = value.length;
      this.checkAll = checkedCount == this.cateList.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.cateList.length;
    },
    // 全选按钮
    handleCheckAllChange(val) {
      // console.log(val);
      this.checkedCategories = val ? this.cateList.map((v) => v.id) : [];
      this.isIndeterminate = false;
    },
    // 视频上传成功回调
    uploadVideoSuccess(response) {
      // console.log(response);
      if (response.message == "文件上传成功") {
        this.post.content = response.data.url;
      }
    },
    // 文章发布
    async publish() {
      if (this.post.type == 1) {
        this.post.content = this.$refs.vueEditor.editor.root.innerHTML;
      }
      // 改造categories数据
      this.post.categories = this.checkedCategories.map((v) => {
        return { id: v };
      });
      let res = await publishPost(this.post);
      console.log("发布文章", res);
      if (res.data.message == "文章发布成功") {
        this.$message({
          type: "success",
          message: "文章发布成功！",
        });
        this.$router.push({ path: "postList" });
      }
      console.log(this.post);
    },
    getToken() {
      return { Authorization: localStorage.getItem("hmtoutiao_back_token") };
    },
  },
};
</script>

<style lang="less" scoped>
</style>